<template>
    <div class="chat" :class="tab==1 ? 'pb0' : ''">
        <div class="moduleHead">
            <router-link v-if="$store.state.user.userInfo.status.isGuest == 1" :to="{ name: 'upgrade' }">
                <span class="icon_gold"></span>
            </router-link>
            <div class="headNav" v-if="chatRoom">
                <span class="tab tab_left" :class="tabClass(0)" @click="swtichTab">
                    <i v-if="unread_message_count>0" class='unreadRed'></i>
                    {{language.chat_tab_one}}
                </span>
                <span class="tab tab_right" :class="tabClass(1)" @click="swtichTab">
                    <i v-if="chatRoomRed" class='unreadRed'></i>
                    {{language.chat_tab_two}}
                </span>
            </div>
            <span v-else>{{language.chat_tab_one}}</span>
            <router-link v-show="tab==1" :to="{ name: 'chatroomMembers' }">
                <span class="right roomMembers"></span>
            </router-link>
        </div>
        <div class="body" ref='divScrollListen'>
            <div v-show="tab==0" class='contact'>
                <promptTip :props="promptData"></promptTip>
                <ul v-show='contactListData.length > 0' class="userlist">
                    <li v-for="(item, index) in contactListData" :key="item.usr_id">
                        <ChatContactLi :item="item" :index="index" ref="items"></ChatContactLi>
                    </li>
                </ul>
                <loading :props="{show:loading}"></loading>
            </div>
            <div v-show="tab==1" class='room'>
                <div class="log" @click='switchMessageLog'>
                    {{showHistory ? 'Hide message history' : 'Show message history'}}
                </div>
                <div class='chatRoomList' ref="roomBox">
                    <MessageList :propsMessagesList="chatRoomListData" :propsType="'chatRoom'" :loading="roomLoading"> </MessageList>
                </div>
            </div>
            <div v-show="tab==1" class='sendMessage'>
                <!--
                <div class="uploadPhoto"></div>
                <div><input accept="image/*" type="file" name="chatMessage_file"></div>
                -->
                <textarea v-model="inputMsg" type="text" placeholder="Compose a message..." spellcheck="false" autocapitalize="off"></textarea>
                <div class="btn sendButton  disable_color" @click='sendChatMessage'> Send </div>
            </div>
        </div>
        <publicDialog :props="this.dialogData">{{errorCode}}</publicDialog>
        <navBottom v-show="tab==0"></navBottom>
    </div>
</template>
<script>
import md5 from 'md5'
import navBottom from './NavBottom'
import MessageList from './MessageList'
import chatPartMixin from '../common/chatPartMixin'
import loading from './Loading'
import promptTip from './PromptTip'
import publicDialog from './PublicDialog'
import ChatContactLi from './ChatContactLi'

let roomStart = false,
    from = 0,
    offset = 20;

export default {
    name: 'chat',

    mixins: [chatPartMixin],

    components: {
        navBottom,
        MessageList,
        loading,
        promptTip,
        publicDialog,
        ChatContactLi
    },

    data() {
        return {
            dialogData: {},
            promptData: {},
            loading: 0,
            roomLoading: 0,
            loadEnd: 0,
            contactFristLoaded: false,
            tab: 0,
            inputMsg: '',
            histroyChatList: [],
            showHistory: false,
            chatRoom: Config.CHAT_ROOM,
            chatRoomRed: false,
            swtichedIndex: -1,
        }
    },

    computed: {

        unread_message_count: function() {
            let num = 0;
            if (this.$store.state.base.siteNumState.unread_message_count) {
                num = parseInt(this.$store.state.base.siteNumState.unread_message_count.new_count);
            }
            return num;
        },

        contactListData: function() {

            let newArr = [];

            //topContactList
            let topContactList = this.$store.state.chat.topContactList;
            topContactList = this.foreachMessageToContact(topContactList);
            topContactList = this.sortTime(topContactList);

            //Recent contact
            let contactList = this.$store.state.chat.contactList;
            contactList = this.foreachMessageToContact(contactList);
            contactList = this.sortTime(contactList);
            //contactList = this.foreachBlock(contactList);

            //unRead contact
            let unReadContactList = this.getUnReadLastMessage(this.$store.state.chat.unReadList);
            unReadContactList = this.foreachMessageToContact(unReadContactList);
            unReadContactList = this.sortTime(unReadContactList);
            //unReadContactList = this.foreachBlock(unReadContactList);

            //Assemble the queue
            newArr = topContactList.concat(unReadContactList, contactList);

            //repeat user
            newArr = _.uniqBy(newArr, 'usr_id');

            //block user
            newArr = this.foreachBlock(newArr);

            //fileter selfs
            newArr = this.filterSelf(newArr);

            //newArr = [];

            return newArr;
        },

        chatRoomListData: function() {
            let messages = [],
                history = [];
            if (this.showHistory) {
                history = this.histroyChatList
            } else {
                history = this.histroyChatList.slice(-5);
            }
            messages = messages.concat(history, this.$store.state.chat.messageHandlerChatRoomList);
            messages = this.foreachMessageToChatRoom(messages)
            //filter 5min time
            messages = this.filterTime(messages);
            return messages;
        }
    },

    created() {

        let tthis = this;
        this.loading = 1;
        this.roomLoading = 1;

        this.tab = this.$route.query.tab ? this.$route.query.tab : 0;

        this.ContactsHandler = {
            proccess: function(obj, args) {
                tthis.loadContactsOK(args.contacts);
            }
        };

        this.ArchiveHandler = {
            proccess: function(obj, args) {
                console.log("Chat ArchiveHandler: ", args);
                if (tthis.isChatroomJid(args.jid)) {
                    tthis.loadChatRoomArchiveOK(args.messages);
                }
            }
        };

        this.$store.watch(
            (state) => state.chat.messageHandlerChatRoomList,
            (arr) => {
                //console.log('messageHandlerChatRoomList', arr, _.last(arr), this.userInfo.account.usr_id);
                if (tthis.tab == 0) {
                    tthis.chatRoomRed = true;
                }
                let message = _.last(arr);
                if (message && message.senderId && parseInt(message.senderId) == parseInt(this.userInfo.account.usr_id)) {
                    tthis.$nextTick(function() {
                        tthis.gotoScrollBottom();
                    });
                }
            }, {
                deep: true
            }
        );

        this.$store.watch(
            (state) => state.chat.unReadCount,
            (num) => {
                //console.log('unReadCount', num);
                tthis.syncSiteMessageStatus(num);
            }, {
                deep: true
            }
        );

        this.$nextTick(function() {
            tthis.gotoScrollBottom();
        });

        this.$root.$on('chat_reset', function() {
            roomStart = false;
            from = 0;
            tthis.histroyChatList = [];
            tthis.loading = 1;
            tthis.roomLoading = 1;
            tthis.loadEnd = 0;
            tthis.contactFristLoaded = false;
        });
    },

    methods: {

        checkoutNoData: function() {
            if (this.contactFristLoaded && this.contactListData.length < 1) {
                this.promptData = {
                    type: 'default',
                    icon:'ico_prompt_message',
                    title: tthis.language.chat_nodata_title,
                    btn: {
                        label: tthis.language.chat_nodata_btn,
                        callback: function() {
                            tthis.$router.push('/browse');
                        }
                    }
                }
            } else {
                this.promptData = {};
            }
        },

        tabClass: function(type) {
            let classStr = '';
            if (this.tab == type) {
                classStr = 'active';
            }
            return classStr;
        },

        swtichTab: function() {
            if (this.tab == 0) {
                this.tab = 1;
                this.getChatRoom();
            } else {
                this.tab = 0;
            }
            this.$router.push({
                name: 'chat',
                query: {
                    'tab': this.tab
                }
            });
        },

        getChatRoom: function() {
            //console.log('getChatRoom',this.contented);
            if (!roomStart && this.contented == 1) {
                roomStart = true;
                //MiniIM.Action.joinRoom(MessageName);
                MiniIM.Action.loadArchive(MessageName, '', MiniIM.TYPE.ROOM, null, 100);
            }
            this.chatRoomRed = false;
        },

        onWinBottomScroll: function(e) {
            if (this.$route.name == 'chat' && this.tab == 0) {
                this.getRecentContacts(from, offset);
            }
        },

        componentConnectOK() {
            console.log('chat,componentConnectOK');
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.RECENT_CONTACTS, this.ContactsHandler);
            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ARCHIVE, this.ArchiveHandler);
            this.loading = 0;
            this.getRecentContacts();
            if (this.tab == 1) {
                this.getChatRoom();
            }
        },

        /*
        loadunreadOK: function() {
            console.log('loadunreadOK');
            this.getRecentContacts();
        },
        */

        filterTime: function(arr) {
            let timePoint = 0;
            for (let i in arr) {
                let messageTime = new Date(arr[i].time).getTime();
                //console.error(messageTime, timePoint, timePoint + (5 * 60 * 1000));
                if (messageTime > timePoint + (5 * 60 * 1000)) {
                    timePoint = messageTime;
                } else {
                    arr[i].formatTime = null;
                }

            }
            return arr;
        },

        filterRepeatId: function(usr_id) {
            let bool = true,
                arr = this.$store.state.chat.contactList;
            for (let i in arr) {
                if (arr[i].usr_id == usr_id) {
                    bool = false;
                }
            }
            return bool;
        },

        sortTime: function(array) {
            var temp, length = array.length;
            for (var i = 0; i < length; i++) {
                for (var j = 0; j < length - 1; j++) {
                    if (new Date(array[j].time).getTime() < new Date(array[j + 1].time).getTime()) {
                        temp = array[j + 1];
                        array[j + 1] = array[j];
                        array[j] = temp;
                    }
                }
            }
            return array;
        },

        foreachMessageToContact(arr) {
            let contactArr = [];
            for (let i in arr) {
                let userInfo = this.getUserObj(this.getContactId(arr[i])).userInfo;
                if (userInfo) {
                    let contactData = this.getContactData(userInfo, arr[i]);
                    if (this.filterRepeatId(contactData.usr_id)) {
                        contactArr.push(contactData);
                    }
                } else {
                    console.log('get userInfo error on contact', arr[i]);
                }
            }
            return contactArr;
        },

        getContactData: function(userInfo, message) {
            let data = {};
            data.username = userInfo.account.username;
            data.usr_id = userInfo.account.usr_id;
            data.gender = userInfo.account.gender;
            data.icon = this.getContactIcon(userInfo);
            data.time = message.time;
            data.formatTime = this.formatDate(message.time, 1);
            data.message = message.message;
            data.unReadNum = this.getUnReadMessageNum(userInfo.account.usr_id);
            data.reply = (message.senderId == this.userInfo.account.usr_id) ? true : false;
            data.isBlocked = userInfo.status.isBlocked;
            data.sysType = message.sysType ? message.sysType : '';
            data.id = message.id;
            return data;
        },

        getUnReadMessageNum: function(usr_id) {
            let num = 0;
            if (this.$store.state.chat.unReadList[usr_id]) {
                num = this.$store.state.chat.unReadList[usr_id].length;
            }
            return num;
        },

        getContactId: function(message) {
            return message.contactId ? message.contactId : message.senderId;
        },

        getContactIcon: function(userInfo) {
            let icon = '',
                arr = userInfo.pictures;

            if (arr && arr[0] && arr[0].icon) {
                icon = arr[0].icon;
            }

            icon = this.getAvatar(userInfo.account.gender, icon);

            //console.log(userInfo.account.gender, icon);
            /*
            if (userInfo.account.username.toLowerCase() == 'support') {

            }
            */
            return icon;
        },

        getUnReadLastMessage(messages) {
            var users = [];
            for (var i in messages) {
                let message = messages[i][0];
                if (message.id !== null && message.id !== 'null') {
                    users.push(message);
                }
            }
            return users;
        },

        getRecentContacts() {
            if (this.loadEnd == 0 && this.loading == 0) {
                this.loading = 1;
                MiniIM.Action.loadRecentContacts(from, offset);
                from = from + offset;
            }
        },

        loadContactsOK: function(contacts) {
            let tthis = this;
            console.log('loadContactsOK');
            //this.contactFristLoaded = true;
            //this.loading = 0;
            if (_.isEmpty(contacts)) {
                this.loadEnd = 1;
                this.contactFristLoaded = true;
                this.checkoutNoData();
            } else {
                let userIds = this.handlerContactMessagesToIds(contacts),
                    callback = function() {
                        tthis.loading = 0;
                        tthis.contactFristLoaded = true;
                        tthis.$store.dispatch('chat_contactHandler', contacts);
                        tthis.checkoutNoData();
                    };
                this.getUsersInfo(userIds, callback);
            }
        },

        loadChatRoomArchiveOK: function(messages) {
            let tthis = this;
            //console.log("ArchiveHandlerChatRoom: ", messages);

            if (messages.length > 0) {
                let callback = function(response) {
                    tthis.roomLoading = 0;
                    tthis.histroyChatList = messages;
                    //tthis.$store.dispatch('chat_chatRoomHandle', messages);
                }
                let ids = this.handlerMessagesToIds(messages);
                this.getUsersInfo(ids, callback);
            } else {
                this.roomLoading = 0;
            }
        },

        foreachMessageToChatRoom: function(arr) {
            let newArr = [];
            for (let i in arr) {
                let userInfo = this.getUserObj(this.getContactId(arr[i])).userInfo;
                if (userInfo) {
                    let data = this.getChatRoomData(userInfo, arr[i]);
                    newArr.push(data);
                } else {
                    console.log('get userInfo error on chatRoom', arr[i]);
                }
            }
            return newArr;
        },

        getChatRoomData: function(userInfo, message) {
            let data = {};
            data.username = userInfo.account.username;
            data.usr_id = userInfo.account.usr_id;
            data.gender = userInfo.account.gender;
            data.icon = this.getContactIcon(userInfo);
            data.time = message.time;
            data.formatTime = this.formatDate(message.time);
            data.message = message.message;
            data.sysType = message.sysType ? message.sysType : '';
            data.id = message.id;
            return data;
        },

        sendChatMessage: function(e) {
            //todo
            if (!this.inputMsg) {
                console.log('no input data');
                return;
            }

            let obj = this.createNewMessage(this.inputMsg);
            MiniIM.Action.sendMessage(MessageName, obj.message, 'groupchat', { id: obj.id });
            this.inputMsg = '';
        },

        createNewMessage(msg) {
            let obj = {};
            obj.sender = this.userInfo.account.username.toLowerCase();
            obj.senderId = this.userInfo.account.usr_id;
            obj.id = md5(msg + new Date().getTime());
            obj.time = new Date();
            obj.message = msg;
            return obj;
        },

        gotoScrollBottom() {
            let el = this.$refs.roomBox;
            if (el) {
                el.scrollTop = el.scrollHeight;
            }
        },

        switchMessageLog() {
            if (this.showHistory) {
                this.showHistory = false;
            } else {
                this.showHistory = true;
            }
        },

        filterSelf(arr) {
            let newArr = [];
            for (let i in arr) {
                if (arr[i].usr_id !== this.userInfo.account.usr_id) {
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        }

    }
}

</script>
<style scoped>
.chat {
    width: 100%;
    background: #f5f7f8;
    padding-top: 44px;
    padding-bottom: 50px;
}

.pb0 {
    padding-bottom: 0;
}

.chat .room {
    background: #f5f7f8;
}

.chat .userlist li {
    min-height: 100px;
}

.chat .userlist li::-webkit-scrollbar {
    width: 0px;
    height: 0px;
}

.chat .userlist li:last-child {
    border-bottom: 0;
}

.chat .moduleHead .headNav .tab {
    position: relative;
}

.chat .moduleHead .right {
    position: absolute;
    width: 60px;
    top: 0;
    right: 0;
    height: 44px;
    line-height: 44px;
    font-size: 18px;
}

.chat .moduleHead .roomMembers {
    background: url(../assets/ico_room_members.png) center no-repeat;
    background-size: auto 21px;
    opacity: 1;
}

.chat .nodata {
    width: 320px;
    position: absolute;
    height: 100px;
    margin: auto;
    left: 0;
    right: 0;
    padding: 30px 10px;
    box-sizing: border-box;
}

.chat .nodataText {
    text-align: center;
}

.chat .nodata button {
    width: 90%;
    margin: auto;
    display: block;
    margin-top: 20px;
}

.chat .nodataH {
    font-size: 15px;
    color: #333;
    padding: 10px;
}

.chat .nodataP {
    font-size: 12px;
    color: #666;
}

.chat .room {
    position: absolute;
    overflow: hidden;
    width: 100%;
    /*height: 510px;*/
    top: 44px;
    left: 0;
    height: calc(100% - 86px);
}

.chat .sendMessage {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    border-top: 1px solid #ccc;
    z-index: 5;
}

.chat .uploadPhoto {
    position: relative;
    width: 40px;
    height: 38px;
    float: left;
    background: url(../assets/ico_message_upload_photo.png) no-repeat center;
    background-size: 20px;
}

.chat input[type="file"] {
    position: absolute;
    left: 0;
    top: 0;
    width: 40px;
    height: 38px;
    opacity: 0;
}


.chat textarea {
    float: left;
    height: 18px;
    padding: 10px 2px;
    border: 0;
    resize: none;
    font-size: 14px;
    background: #fff;
    width: calc(100% - 65px);
    margin: 1px 0px 1px 5px;
    overflow: hidden;
    line-height: 18px;
}

.chat .sendButton {
    padding: 0;
    width: 45px;
    height: 30px;
    line-height: 30px;
    font-size: 13px;
    color: #F2F9F3;
    float: right;
    text-align: center;
    margin: 5px;
    border-radius: 3px;
    border: 0px;
}

.chat .log {
    height: 30px;
    color: #666;
    font-size: 14px;
    text-align: center;
    width: 100%;
    line-height: 30px;
    background: #dcdcdc;
    position: absolute;
}

.chat .chatRoomList {
    height: calc(100% - 30px);
    overflow-x: hidden;
    overflow-y: auto;
    box-sizing: border-box;
    margin-top: 30px;
}

.chat .moduleHead .chatRoomRed {
    position: absolute;
    width: 5px;
    height: 5px;
    background: #f64747;
    border-radius: 10px;
    margin-left: 65px;
    margin-top: 2px;
}

.chat .moduleHead .unreadRed {
    position: absolute;
    right: 8px;
    top: 5px;
    width: 6px;
    height: 6px;
    background: #f64747;
    border-radius: 50%;
}

</style>
